package com.shenzw.common.sign;

import lombok.Data;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 验签controller
 * @author: shenzw
 * @date: 2024/10/25
 */
@RestController
@RequestMapping("/verify")
public class VerificationController {

    @PostMapping
    @VerifySignatureAnnotation
//    public String verifyMessage(@RequestParam String plain, @RequestParam byte[] signature) {
    public String verifyMessage(@RequestBody VerificationRequest request) {
        // 此方法会自动验签
        // 如果验签成功, 继续后面的操作逻辑
        VerificationRequestBody verificationRequestBody = convertToEntity(request.getData(), VerificationRequestBody.class);
        System.out.println("员工号: " + verificationRequestBody.getEmployeeId());
        // 校验员工是否存在
        // ....
        return "Message verified successfully";
    }

    public static <T> T convertToEntity(String input, Class<T> clazz) {
        T instance;
        try {
            // 创建实体类实例
            instance = clazz.getDeclaredConstructor().newInstance();
            Map<String, String> params = new HashMap<>();

            // 分割字符串并解析参数
            String[] pairs = input.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0];
                    String value = keyValue[1];

                    // URL 解码
                    try {
                        value = URLDecoder.decode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    params.put(key, value);
                }
            }

            // 设置属性
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String fieldName = entry.getKey();
                String fieldValue = entry.getValue();
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true); // 允许访问私有字段
                field.set(instance, fieldValue);
            }

            return instance;
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert string to entity", e);
        }
    }
}

/**
 * 统一类处理
 */
@Data
class VerificationRequest {
    private String data;

    private byte[] signature;

    // Getters and setters
}

@Data
class VerificationRequestBody {

    private String employeeId;

    private String plain;

    private String aa;
}